package ljl.codetop300;

import java.util.Arrays;

public class _59_spiral_matrix_2 {

  /**
   * 这不就是打印螺旋矩阵，额外加了个填数操作吗？
   * 而且这个是个正方形，理论上更简单了
   * 1 1 1
   * 1 1 1
   * 1 1 1
   */
  static class test {
    public static void main(String[] args) {
      int[][] res = new test().generateMatrix(4);
      for (int[] re : res) {
        System.out.println(Arrays.toString(re));
      }
    }

    public int[][] generateMatrix(int n) {
      int[][] res = new int[n][n];
      int k = 1;
      int left = 0, right = n - 1;
      int top = 0, bottom = n - 1;
      while (left <= right && top <= bottom) {
        for (int i = left; i <= right; i++) {
          res[top][i] = k++;
        }
        for (int i = top + 1; i <= bottom; i++) {
          res[i][right] = k++;
        }
        if (left < right) {
          for (int i = right - 1; i >= left ; i--) {
            res[bottom][i] = k++;
          }
          for (int i = bottom - 1; i > top ; i--) {
            res[i][left] = k++;
          }
        }
        top++;
        right--;
        bottom--;
        left++;
      }
      return res;
    }
  }

  static class lu_fei {
    public int[][] generateMatrix(int n) {
      int l = 0, r = n - 1, t = 0, b = n - 1;
      int[][] mat = new int[n][n];
      int num = 1, tar = n * n;
      while(num <= tar){
        for(int i = l; i <= r; i++) mat[t][i] = num++; // left to right.
        t++;
        for(int i = t; i <= b; i++) mat[i][r] = num++; // top to bottom.
        r--;
        for(int i = r; i >= l; i--) mat[b][i] = num++; // right to left.
        b--;
        for(int i = b; i >= t; i--) mat[i][l] = num++; // bottom to top.
        l++;
      }
      return mat;
    }
  }

  /**
   * 为什么 copy 他的因为他的解法简单
   */
  static class copy_lu_fei {
    public int[][] generateMatrix(int n) {
      int[][] res = new int[n][n];
      int num = 1, target = n * n;
      int l = 0, r = n - 1, t = 0, b = n - 1;
      while (num <= target) {
        for (int i = l; i <= r; i++) res[t][i] = num++;
        t++;
        for (int i = t; i <= b; i++) res[i][r] = num++;
        r--;
        for (int i = r; i >= l; i--) res[b][i] = num++;
        b--;
        for (int i = b; i >= t; i--) res[i][l] = num++;
        l++;
      }
      return res;
    }
  }
}
